﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Cache;
using System.Text;
using System.Data.SqlClient;
using System.Windows.Forms;
using DevExpress.XtraEditors;

using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using System.Deployment.Application;

namespace ProgramMain.Framework
{
    public enum ExtendedPropertieTypes
    {
        VertexCurveElementAll = 1,
        VertexConnectionLineAll =2,
        VertexCurveElementOnlyCable = 3,
        VertexConnectionLineOnlyCable = 4,
        VertexCurveElementOnlyCableBox = 5,
        VertexConnectionLineOnlyCableBox = 6
    }
    public static class GlobalData
    {
        public static SqlConnection SqlCon = null;
        private static GridViewLayoutHistory GridViewLayoutHistory = new GridViewLayoutHistory();

        static GlobalData()
        {
            try
            {
                ReadGridViewLayoutHistory();
            }
            catch (Exception ex)
            {
                //do nothing
                System.Diagnostics.Trace.WriteLine(ex.Message);
            }
        }

        public static bool OpenSqlConnection(string strConn)
        {
            try
            {
                SqlCon = new SqlConnection();
                SqlCon.ConnectionString = strConn;
                SqlCon.Open();
            }
            catch (Exception)
            {
                SqlCon = null;
                return false;
            }
            return true;
        }

        public static System.Drawing.Icon DefaultIcon()
        {
            return System.Drawing.Icon.ExtractAssociatedIcon(Application.ExecutablePath);
        }

        public static void SaveHistory()
        {
            SaveGridViewLayoutHistory();

            Properties.Settings.Default.Save();
        }

        public static void ClearHistory()
        {
            foreach(Form frm in Program.MainForm.MdiChildren)
            {
                if (frm is frmBase)
                    frm.Close();
            }
            Properties.Settings.Default.GridViewLayoutHistory = "";

            Properties.Settings.Default.Save();
        }

        public static void SaveGridViewLayoutHistory()
        {
            Properties.Settings.Default.GridViewLayoutHistory = GridViewLayoutHistory.Dictionary;
        }

        public static void ReadGridViewLayoutHistory()
        {
            GridViewLayoutHistory.Dictionary = Properties.Settings.Default.GridViewLayoutHistory;
        }

        public static void StoreGridLayoutHistory(string gridID, string Layout)
        {
            GridViewLayoutHistory.StoreLayoutHistory(gridID, Layout);
        }

        public static string ReadGridLayoutHistory(string gridID)
        {
            return GridViewLayoutHistory.ReadLayoutHistory(gridID);
        }

        private static bool m_bUpdateMode = false;

        public static bool UpdateApplication()
        {
            if (m_bUpdateMode) return true;
            try
            {
                if (ApplicationDeployment.IsNetworkDeployed)
                {
                    ApplicationDeployment updateCheck = ApplicationDeployment.CurrentDeployment;
                    UpdateCheckInfo info = updateCheck.CheckForDetailedUpdate();

                    if (info.UpdateAvailable)
                    {
                        try
                        {
                            m_bUpdateMode = true;
                            if (XtraMessageBox.Show("Доступно обновление программы. После обновления потребуется перезапуск приложения. Продолжить?", "Внимание", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                            {
                                updateCheck.Update();
                                XtraMessageBox.Show("Приложение обновлено требуется перезапуск", "Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                Application.Restart();
                            }
                        }
                        finally
                        {
                            m_bUpdateMode = false;
                        }
                        return true;
                    }
                } else
                {
                    try
                    {
                        m_bUpdateMode = true;
                        
                        StreamReader reader = DownloadTxtFile(Properties.Settings.Default.AppVersionCheckPath);
                        if (reader != null)
                        {
                            string AppVersion = reader.ReadLine().Trim();
                            if (AppVersion.Length > 0 && AppVersion != Properties.Settings.Default.AppVersion)
                            {
                                Stream app = DownloadFile(Properties.Settings.Default.AppInstallPath);
                                if (app != null)
                                {
                                    String tempPath = Path.GetTempPath();
                                    tempPath = Path.Combine(tempPath, Properties.Settings.Default.AppInstallName);
                                    if(File.Exists(tempPath))
                                        try
                                        {
                                            File.Delete(tempPath);
                                        }
                                        catch (Exception)
                                        {
                                        }
                                    using (var fileStream = new FileStream(tempPath, FileMode.Create))
                                    {
                                        app.CopyTo(fileStream);
                                        fileStream.Flush();
                                        fileStream.Close();
                                    }

                                    if (
                                        XtraMessageBox.Show(
                                            "Доступно обновление программы. После обновления потребуется перезапуск приложения. Продолжить?",
                                            "Внимание", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) ==
                                        DialogResult.Yes)
                                    {
                                        System.Diagnostics.Process.Start(tempPath);
                                        Application.Exit();
                                    }
                                }
                            }
                            return false;
                        }
                    }
                    finally
                    {
                        m_bUpdateMode = false;
                    }
                    
                    return true;
                }

                return false;
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return true;
            }
        }

        public static string GetAssemblyTitle()
        {
            string aTitle = "Simple Optic Net - модуль оптико-волоконной сети";
            System.Reflection.Assembly thisAssembly = Program.MainForm.GetType().Assembly;
            object[] attributes = thisAssembly.GetCustomAttributes 
               (typeof(System.Reflection.AssemblyTitleAttribute), false);
            if (attributes.Length == 1)
            {
               aTitle = ((System.Reflection.AssemblyTitleAttribute) attributes[0]).Title;
            }
            return aTitle;
        }

        public static MemoryStream DownloadFile(string urlNav)
        {
            MemoryStream mStream = new MemoryStream();
            try
            {
                HttpWebRequest oRequest = (HttpWebRequest)HttpWebRequest.Create(urlNav);
                oRequest.UserAgent = "simplebilling";
                oRequest.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
                HttpWebResponse oResponse = (HttpWebResponse)oRequest.GetResponse();
                oResponse.GetResponseStream().CopyTo(mStream);
                mStream.Position = 0;
            }
            catch (Exception)
            {
                mStream = null;
            }
            return mStream;
        }

        public static StreamReader DownloadTxtFile(string urlNav)
        {
            Stream mStream = DownloadFile(urlNav);
            if (mStream != null)
            {
                return new StreamReader(mStream);
            }
            return null;
        }

        public static void CopyTo(this Stream src, Stream dest)
        {
            if (dest != null)
            {
                int readCount;
                
                var buffer = new byte[1024];
                while ((readCount = src.Read(buffer, 0, buffer.Length)) != 0)
                    dest.Write(buffer, 0, readCount);
                
                src.Position = 0;
            }
        }
        
        public class ListEventArgs<T> : EventArgs
        {
            public List<T> IDList { get; protected set; }

            public ListEventArgs()
            {
                this.IDList = new List<T>();
            }

            public ListEventArgs(List<T> IDList)
            {
                this.IDList = IDList;
            }
        }

        public class ListEventArgs : ListEventArgs<int>
        {
            public ListEventArgs(List<int> IDList)
            {
                this.IDList = IDList;
            }
        }

        public static void ChangeConnectionString(string Value)
        {
            //if (BaseSecurity.CheckSecurityAccessType(BaseSecurity.UserAccessType.ManagerAccess) == BaseSecurity.SuperBool.True)
            //{
            //    Properties.Settings.Default["programConnectionString"] =
            //        Properties.Settings.Default.managerConnectionString;
            //}
            //else
            //{
            //    Properties.Settings.Default["programConnectionString"] =
            //        Properties.Settings.Default.techConnectionString;
            //}

            //Properties.Settings.Default.Save();
        }
    }
}
